/**
 * @fileOverview
 * @author iNahoo
 * @since 2022/3/2.
 */

const { writeFileSync } = require('fs');

// 创建双映射
function createDupMapping(arr, same) {
  const mp = {};
  arr.forEach((v, i) => {
    mp[v] = i;
    mp[i] = v;
  });

  same && Object.keys(same).forEach(key => {
    mp[key] = mp[same[key]];
  })
  return mp;
}

/**
 * @param headers {[String,String|Function][]}
 * @param data {any[]}
 * @param target {String}
 */
function generateCSV(headers, data, target) {
  const str = headers.map(([name]) => name).join(',') + '\n' + data.map(row => {
    return headers.map(([name, handler]) => {
      if (!handler) {
        handler = name;
      }

      if (typeof handler === 'string') {
        const key = handler;
        handler = r => r[key];
      }

      return handler(row);
    }).join(',');
  }).join('\n');

  writeFileSync(target, str, 'utf-8');
}

const ATTR_ID_MAP = createDupMapping(['风', '火', '冰', '电', '光'], { ['雷']: '电' });

module.exports = {
  generateCSV,
  createDupMapping,
  ATTR_ID_MAP,
}
